import { Form, Input, Button } from "antd-mobile";
import { useCountDown } from "ahooks";
import { useState } from "react";
import axios from "axios";
import { useNavigate } from "react-router-dom";

const Login = () => {
  const navigate = useNavigate()
  const [form] = Form.useForm();
  const [targetDate, setCountDown] = useState();
  const [count] = useCountDown({
    targetDate,
  });
  const num = Math.floor(count / 1000);

  const handleClick = () => {
    setCountDown(Date.now() + 60 * 1000);

    form.validateFields(["tel"]).then(async ({ tel }) => {

      const resp = await axios.get("/api/login/code", { params: { tel: tel } });
      console.log("验证码", resp.data.data);
      form.setFieldValue("telCode", resp.data.data);
    });
  };

  const onFinish = async (values) => {
    const resp = await axios.post("/api/login/tel", values);
    console.log(resp.data)
    const { code, data, message } = resp.data;
    if(code === 200) {
      localStorage.setItem("token", data.token);
      localStorage.setItem("userInfo", JSON.stringify(data.userInfo));
      navigate('/')
    }  else {
      alert(message)
    }
  };
  return (
    <div>
      <Form
        onFinish={onFinish}
        form={form}
        layout="horizontal"
        footer={
          <Button block type="submit" color="primary" size="large">
            提交
          </Button>
        }
      >
        <Form.Item
          name="tel"
          label="手机号"
          rules={[{ required: true, message: "手机号不能为空" }]}
        >
          <Input onChange={console.log} placeholder="请输入手机号" />
        </Form.Item>
        <Form.Item
          name="telCode"
          label="短信验证码"
          extra={
            <Button onClick={() => handleClick()}>
              {num === 0 ? "获取验证码" : `${num}秒后重试`}
            </Button>
          }
        >
          <Input placeholder="请输入" />
        </Form.Item>
      </Form>
    </div>
  );
};

export default Login;
